<?php

namespace App\Console\Commands;

use App\Common\Constant\Params;
use App\Models\Merchant;
use App\Models\OldOrder;
use App\Models\Order;
use App\Models\OrderDetail;
use App\Models\OrderGoods;
use App\Models\OrderOffer;
use App\Models\OrderStatus;
use App\Services\IStorageService;
use DB;
use Illuminate\Console\Command;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Support\Collection;
use Log;

class importOrder extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'import:old-order {offset=0}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '导入订单';

    private $exceptionHandler;
    private $storageService;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(ExceptionHandler $exceptionHandler,IStorageService $storageService)
    {
        parent::__construct();

        $this->exceptionHandler = $exceptionHandler;
        $this->storageService = $storageService;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $bar = $this->output->createProgressBar(OldOrder::count());
        $offset = $this->argument('offset');

        $areas = getAreas();
        $area_names = [];
        foreach ($areas as $area){
            $area_names[$area['n']] = $area;
        }

        OldOrder::orderBy('o_id')->chunk(100, function ($orders) use (&$bar,&$areas,&$area_names,&$offset){
            foreach ($orders as $model) {
                if ($bar->getProgress() < $offset){
                    $this->line("\tOrder [{$model->o_number}] skip");
                    $bar->advance();
                    continue;
                }
                if (Order::where('order_number',$model->o_number)->count()){
                    $this->line("\tOrder [{$model->o_number}] exists");
                    $bar->advance();
                    continue;
                }
                if (!is_numeric(trim($model->o_number))){
                    $this->line("\tOrder [{$model->o_number}] order_number wrong");
                    $bar->advance();
                    continue;
                }

                DB::beginTransaction();
                try{
                    //订单
                    $confirm_code = random(6,'PNUMBER');
                    $service_type = [
                        1=>Params::MERCHANT_SERVICE_TYPE_DELIVERY_INSTALL,
                        2=>Params::MERCHANT_SERVICE_TYPE_INSTALL,
                        3=>Params::MERCHANT_SERVICE_TYPE_REPAIR,
                        4=>Params::MERCHANT_SERVICE_TYPE_DELIVERY,
                    ][$model->o_servicetype];
                    $order = Order::create([
                        'order_number'=>trim($model->o_number),
                        'merchant_id'=>$model->o_me_id,
                        'service_category'=>Params::SERVICE_CATEGORY_FURNITURE,//家具类
                        'service_type'=>$service_type,
                        'confirm_code'=>$confirm_code,
                        'push_time'=>$model->o_createtime ? : ($model->o_paytime ? : 0),
                        'master_id'=>$model->o_master,
                        'offer_price'=>$model->o_price,
                        'merchant_price'=>$model->o_trueprice,
                        'appoint_time'=>$model->o_meettime ? : 0,
                        'pay_time'=>$model->o_paytime ? : 0,
                    ]);
                    if (!$order){
                        throw new \Exception('order create fail');
                    }
                    $ret = OrderOffer::create([
                        'order_id'=>$order->id,
                        'master_id'=>$model->o_master,
                        'price'=>$model->o_price,
                        'status'=>Params::OFFER_STATUS_EMPLOYED
                    ]);
                    if (!$ret){
                        throw new \Exception('order offer create fail');
                    }

                    //订单商品
                    if ($model->o_cargo){
                        OrderGoods::create([
                            'order_id'=>$order->id,
                            'goods_id'=>0,
                            'goods_type'=>Params::GOODS_CATEGORY_OTHER,
                            'goods_name'=>$model->o_cargo,
                            'goods_mark'=>$model->o_cargo,
                            'goods_num'=>1,
                            'goods_img'=>$model->o_cargoimg ? $this->storageService->saveUrl('http://www.lebangdaojia.com/upload/'.$model->o_cargoimg) : '',
                            'goods_price'=>0,
                        ]);
                    }else{
                        $cargolistid = json_decode($model->o_cargolistid,true);//ID
                        $cargolistname = json_decode($model->o_cargolistname,true);//名称
                        $cargolistnum = json_decode($model->o_cargolistnum,true);//数量
                        $cargolistcat = json_decode($model->o_cargolistcat,true);//类目
                        $cargolistprice = json_decode($model->o_cargolistprice,true);//价格
                        $cargolistimg = json_decode($model->o_cargolistimg,true);//图片
                        $crgolistps = json_decode($model->o_cargolistps,true);//备注
                        Collection::make($cargolistid)->each(function($item,$key) use ($order,$cargolistname,$cargolistnum,$cargolistcat,
                            $cargolistprice,$cargolistimg,$crgolistps){
                            return OrderGoods::create([
                                'order_id'=>$order->id,
                                'goods_id'=>$item,
                                'goods_type'=>@$cargolistcat[$key] ? : Params::GOODS_CATEGORY_OTHER,
                                'goods_name'=>@$cargolistname[$key] ? : '',
                                'goods_mark'=>@$crgolistps[$key] ? : '',
                                'goods_num'=>max(intval(@$cargolistnum[$key]),1),
                                'goods_img'=>@($cargolistimg[$key] ? $this->storageService->saveUrl('http://www.lebangdaojia.com/upload/'.$cargolistimg[$key]) : ''),
                                'goods_price'=>@$cargolistprice[$key] ? : 0,
                            ]);
                        });
                    }

                    $address = explode(' ',$model->o_custaddress);
                    if (count($address) == 4){
                        $customer_area = $address[2];
                        $customer_area_id = @$area_names[$customer_area]['i'] ? : 0;
                    }else if (count($address) == 3){
                        $customer_area = $address[1];
                        $customer_area_id = @$area_names[$customer_area]['i'] ? : 0;
                    }else{
                        $customer_area_id  = 0;
                    }
                    //订单信息详情
                    if ($model->o_me_id){
                        $merchant = Merchant::find($model->o_me_id);
                    }else{
                        $merchant = null;
                    }

                    @$district = $areas[$customer_area_id];
                    @$city = $areas[$district['p']];
                    @$province = $areas[$city['p']];
                    @$customer_area = implode('-',[$province['n'],$city['n'],$district['n']]);

                    $ret = OrderDetail::create([
                        'order_id'=>$order->id,
                        'customer_name'=>$model->o_customer,
                        'customer_phone'=>$model->o_custphone,
                        'customer_area_id'=>$customer_area_id,
                        'customer_address'=>$model->o_custaddress,
                        'customer_elevator'=>$model->o_elevator,
                        'customer_floor'=>$model->o_floor,
                        'customer_tmall_number'=>$model->o_checknumber,
                        'customer_memark'=>$model->o_memark,
                        'logistics_packages'=>$model->o_logisticsnum,
                        'logistics_ticketnumber'=>$model->o_logisticsnumber,
                        'logistics_name'=>'',
                        'logistics_phone'=>$model->o_logiphone,
                        'logistics_address'=>$model->o_logistiaddress,
                        'logistics_consignee'=>$model->o_logisname,
                        'logistics_mark'=>$model->o_logimark,
                        'merchant_name'=>$merchant ? $merchant->me_username : '',
                        'merchant_phone'=>$merchant ? $merchant->me_phone : '',
                        'customer_area'=>$customer_area ? : '',
                    ]);
                    if (!$ret){
                        throw new \Exception('order detail create fail');
                    }
                    //订单状态
                    $ret = OrderStatus::create([
                        'order_id'=>$order->id,
                        'merchant_status'=>Params::ORDER_MERCHANT_STATUS_SUCCESS,
                        'master_status'=>Params::ORDER_MASTER_STATUS_SUCCESS,
                        'logistics_status'=>Params::LOGISTICS_STATUS_ARRIVED,
                        'except_status'=>Params::ORDER_EXCEPT_NORMAL,
                        'refund_status'=>Params::ORDER_REFUND_NORMAL,
                        'arbitrate_status'=>Params::ORDER_ARBITRATE_NORMAL,
                        'evaluate_status'=>Params::ORDER_EVALUATE_NOTYET,
                        'appoint_time'=>$model->o_meettime ? : ($model->o_createtime ? : 0),
                        'finish_time'=>$model->o_createtime ? : ($model->o_paytime ? : 0),
                        'order_success_time'=>$model->o_createtime ? : ($model->o_paytime ? : 0),
                    ]);
                    if (!$ret){
                        throw new \Exception('order status create fail');
                    }

                    DB::commit();
                    $this->info("\tOrder [{$model->o_number}] success");
                }catch (\Exception $e){
                    DB::rollBack();
                    $this->error("\tOrder [{$model->o_number}] fail\nerror: ".$e->getMessage()." in ".$e->getFile()."[".$e->getLine()."]\n");
                    Log::error("\tOrder [{$model->o_number}] fail\nerror: ".$e->getMessage()." in ".$e->getFile()."[".$e->getLine()."]\n");
                    $this->exceptionHandler->report($e);
                }

                $bar->advance();
            }
        });

        $bar->finish();

    }
}
